use std::collections::HashMap;

#[allow(unused)]
fn part1() {
    println!(
        "{}",
        include_bytes!("./input.txt")
            .split(|&b| b == b'\n')
            .map(|line| {
                let first : usize = (line.iter().find(|b| b.is_ascii_digit()).unwrap() - b'0') as usize;
                let last  : usize = (line.iter().rev().find(|b| b.is_ascii_digit()).unwrap() - b'0') as usize;
                (10 * first + last) as usize
            })
            .sum::<usize>()
    );
}

const NUMS: [&[u8]; 9] = [
    b"one", b"two", b"three", b"four", b"five", b"six", b"seven", b"eight", b"nine"
];

#[allow(unused)]
fn part2() {
    println!("{}",
        include_bytes!("./input.txt")
        .split(|&b| b == b'\n')
        .map(|line|{
            let first =
                (0..line.len()).find_map(|i| num(line, i)).unwrap();
            let last =
                (0..line.len()).rev().find_map(|i| num(line, i)).unwrap();
            10 * first + last
        })
        .sum::<usize>()
    );
}

fn num(line: &[u8], i: usize) -> Option<usize> {
    match line[i].is_ascii_digit() {
        true => Some((line[i] - b'0') as usize),
        false => {
            NUMS
            .iter()
            .enumerate()
            .find(|(_, name)| line[i..].starts_with(name))
            .map(|(num, _)| num + 1)
        }
    }
}

fn main() {
    // part1();
    let numbers_map = HashMap::from([
        ("1", 1),
        ("2", 2),
        ("3", 3),
        ("4", 4),
        ("5", 5),
        ("6", 6),
        ("7", 7),
        ("8", 8),
        ("9", 9),
        ("one", 1),
        ("two", 2),
        ("three", 3),
        ("four", 4),
        ("five", 5),
        ("six", 6),
        ("seven", 7),
        ("eight", 8),
        ("nine", 9),
    ]);

    let contents = std::fs::read_to_string("./day01/src/input.txt").unwrap();

    let sum = contents
        .lines()
        .fold(0, |acc, line| {
            let mut first: i32 = -1;
            let mut last: i32 = -1;
            for (i, _) in line.chars().enumerate() {
                for kv in numbers_map.iter() {
                    let size = kv.0.len();
                    if i + size > line.len() {
                        continue;
                    }
                    if &line[i..(i+size)] == *kv.0 {
                        last = *kv.1;
                        if first == -1 {
                            first = *kv.1;
                        }
                    }
                }
            }
            acc + first * 10 + last
        });

    println!("{sum}");
}
